package com.bjy.qa.util.security;

import com.bjy.qa.entity.user.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Security 工具类，获取当前登录用户信息
 */
public class SecurityUtils {
    /**
     * 获取当前登录用户信息
     * @return User 对象
     */
    public static User getCurrentUser() {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) usernamePasswordAuthenticationToken.getPrincipal();
        return loginUser.getUser();
    }

    /**
     * 获取当前登录用户信息的 LoginUser 对象
     * @return LoginUser 对象
     */
    public static LoginUser getCurrentLoginUser() {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return  (LoginUser) usernamePasswordAuthenticationToken.getPrincipal();
    }

    /**
     * 获取当前登录用户 id
     * @return 用户 id
     */
    public static Long getCurrentUserId() {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) usernamePasswordAuthenticationToken.getPrincipal();
        return loginUser.getUser().getId();
    }

    /**
     * 获取当前登录用户名
     * @return 用户名
     */
    public static String getCurrentUserName() {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) usernamePasswordAuthenticationToken.getPrincipal();
        return loginUser.getUser().getName();
    }

    /**
     * 获取当前登录用户选择的当前 公司 id
     * @return 公司 id
     */
    public static Long getCurrentUserCompanyId() {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) usernamePasswordAuthenticationToken.getPrincipal();
        return loginUser.getUser().getCompanyId();
    }

    /**
     * 获取当前登录用户选择的当前 项目 id
     * @return 项目 id
     */
    public static Long getCurrentUserProjectId() {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) usernamePasswordAuthenticationToken.getPrincipal();
        return loginUser.getUser().getProjectId();
    }
}
